import { useReducer } from 'react'


// 初始state
const defaultState = { num: 0 }

// state改变函数reducer
const reducer = (state, action) => {
    const newState = { ...state };
    const { type, payload } = action;
    switch (type) {
        case "DECREMENT":
            newState.num > 0 ? newState.num -= payload : 0;
            break;
        case "INCREMENT":
            newState.num += payload;
            break;
        default:
            break;
    }
    return newState;
}

const useNumReducer = () => {
    const [state, dispatch] = useReducer(reducer, defaultState);
    return [state, dispatch];
}

export default useNumReducer